import 'package:flutter/material.dart';
import 'component.dart';
import 'overview_api_provider.dart';
import 'models/rank_model.dart';
import 'global/event_bus.dart';

const statisItems = [
  {'name':'毛利差排名', 'key': 'profitAmount'},
  {'name':'存款', 'key':'totalDepositAmount'},
  {'name':'提款', 'key':'totalAtmAmount'},
  {'name':'有效投注额', 'key':'betValidAmount'},
  {'name':'有效用户数', 'key':'totalDepositCount'},
  {'name':'注册人数', 'key':'totalRegistCount'},
  {'name':'首存金额', 'key':'depositFirstAmount'},
  {'name':'首存人数', 'key':'depositFirstCount'},
  {'name':'次存金额', 'key':'depositSecondAmount'},
  {'name':'次存人数', 'key':'depositSecondCount'},
  {'name':'PC人数', 'key':'depositPcCount'},
  {'name':'H5人数', 'key':'depositWapCount'},
  {'name':'新客存款总额', 'key':'newClientTotalDeposit'},
  {'name':'新客提款总额', 'key':'newClientTotalAtm'},
  {'name':'新客有效投注额', 'key':'newClientBetValidAmount'},
  {'name':'新客人数', 'key':'newClientCount'},

];

class RankViewer extends StatefulWidget {
  RankViewer({Key key}):super(key:key);
  @override
  _RankViewState createState() {
    return _RankViewState();
  }
}

class _RankViewState extends State<RankViewer> {
  OverViewProvider provider = OverViewProvider();
  int orderIndex; //类型
  int dateIndex; //日期
  int topTypeIdx; //指标
  bool isLoading = false;
  bool hasError = false;
  RankDataModel model;
  @override
  void initState() {
    super.initState();
    orderIndex = 1; //order 类型
    topTypeIdx = 0;  //指标
    dateIndex = 1; //日期
    getRankData();
  }

  getRankData() async{
    isLoading = true;
    hasError = false;
    setState(() {});
    try {
      final orderItem = orderIndex == 0 ? null : (orderIndex == 1 ? 'H': 'Z');
      final topType = statisItems[topTypeIdx]['key'];
      model = await provider.fetchRankData(orderItem, dateIndex, topType);
      if(model!=null && model.resObj!=null && model.resObj.length>0) {
        bus.emit('nowdate', model.resObj[0].nowDate);
      }
      isLoading = false;
      hasError = false;
      setState(() {});
    } catch(e) {
      print(e);
      hasError = true;
      isLoading = false;
      setState(() {});
    }

  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(5),
      child: Row(
        children: <Widget>[makeTableHeader(), makePad()],
      ),
    );
  }

  SizedBox makeTableHeader() {
    return SizedBox(
      width: 100,
      height: 400,
      child: ListView(
          children: statisItems.map((e) {
            int idx = statisItems.indexOf(e);
            bool isSelectItem = (idx == topTypeIdx);
        return DecoratedBox(
          child: GestureDetector(
            onTap: (){
              topTypeIdx = idx;
              getRankData();
            },
              child: SizedBox(
            width: 100,
            height: 50,
            child: Center(
              child: Text(e['name'], style: TextStyle(color: Color(0xFF758BB5)),),
            ),
          )),
          decoration: BoxDecoration(
              border: isSelectItem? Border(left: BorderSide(width: 2, color: Colors.cyan)):null
          ),
        );
      }).toList()),
    );
  }

  Expanded makePad() {
    var noData = false;
    if(model == null || model.resObj == null || model.resObj.length == 0) {
      noData = true;
    }
    Widget contentWidget = null;
    if(isLoading) {
      contentWidget = Center(
        child: CircularProgressIndicator(),
      );
    }
    if(hasError) {
      print('hello error');
      contentWidget = ErrorBlock(errorType: ErrorType.noData,);
    }
    if(noData) {
      contentWidget = Container(child:ErrorBlock(errorType: ErrorType.noData,));
    }
    bool isvalid = model != null&&model.resObj!=null&&model.resObj.length>0;
    final maxPlatValue = isvalid? model.resObj.reduce((m1, m2)=> m1.topValue > m2.topValue? m1:m2).topValue:0;
    final persents = isvalid?model.resObj.map((e) => e.topValue / maxPlatValue).toList():[];
    return Expanded(
      child: Column(
        children: <Widget>[
          Container(
            height: 50,
            child: Row(
              children: <Widget>[
                FilterChooser(
                  filterItems: ['全部','18基础型','19舒适型'],
                  currentIndex: orderIndex,
                  onClick: (idx){
                    orderIndex = idx;
                    getRankData();
                  },
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Text('排行统计', style: TextStyle(color: Colors.white, fontSize: 15), ),
                ),
                FilterChooser(
                  filterItems: ['实时', '昨日', '前日', '本周', '上周', '本月', '上月', '上上月'],
                  currentIndex: dateIndex-1,
                  onClick: (idx){
                    dateIndex = idx+1;
                    getRankData();
                  },
                )
              ],
            ),
          ),
          Expanded(
            child: contentWidget!=null?contentWidget:ListView(
              children: model.resObj.map((e) {
                int idx = model.resObj.indexOf(e);
                return Container(
                  height: 25,
                  child: Row(
                    children: <Widget>[
                      Text(
                        (idx + 1).toString(),
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 5),
                        child: Text(e.domain,
                            style: TextStyle(color: Color(0xFF758BB5))),
                      ),
                      Image(
                          width: 5 * persents[idx] * 90,
                          height: 10,
                          image: AssetImage('images/progress.png'),
                          fit: BoxFit.fill,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 5),
                        child: Text(e.topValue.toString(), style: TextStyle(color: Colors.white, fontSize: 12),),
                      )

                    ],
                  ),
                );
              }).toList(),
            ),
          )
        ],
      ),
    );
  }
}
